import Canvas from './canvas';
import Group from './group';
import { draw } from '@/utils';

/**
 * 画板类
 */
export default class Board extends Group {
  className = 'Board'; // 类名
  draggable = false; // 画板不可拖动
  constructor(config = {}) {
    super(config);
    // 是否裁剪绘图区域
    this.clip = config.clip ?? true;
    // 是否半透明方式显示裁剪区域
    this.clipShow = config.clipShow ?? false;
    // 背景纯色填充颜色
    this.bgFillColor = config.bgFillColor ?? 'transparent';
    // 是否展示画板 name
    this.nameShow = config.nameShow ?? false;
  }
  // 更新画板
  update() {
    // 按照深度属性排序子节点
    this.nodes.sort((a, b) => a.zIndex - b.zIndex);
  }
  // 绘制主要内容
  drawMain(ctx, isExport) {
    const { nameShow, name, nodes, width, height, opacity, clip, clipShow, bgFillColor, stage } = this;
    // 绘制画板 name
    if (nameShow && !isExport) {
      const calc = (num) => this.calc(num, stage);
      draw.text(ctx, {
        text: name,
        x: 0,
        y: calc(-8),
        color: '#666',
        fontSize: calc(12),
        maxWidth: width,
      });
    }
    // 裁剪画板绘图区域
    if (clip && !isExport) {
      // 以半透明方式显示裁剪区域
      if (clipShow) {
        ctx.globalAlpha = opacity * 0.5;
        nodes.forEach((node) => node.draw(ctx));
        ctx.globalAlpha = opacity;
      }
      ctx.beginPath();
      ctx.rect(0, 0, width, height);
      ctx.clip();
    }
    // 绘制画板背景
    ctx.save();
    if (!isExport) {
      // 填充马赛克背景
      ctx.fillStyle = stage.scale >= 0.1 ? ctx.createPattern(Board.mosaicPattern, 'repeat') : '#F6F6F6';
      ctx.fillRect(0, 0, width, height);
    }
    // 背景纯色填充
    ctx.fillStyle = bgFillColor;
    ctx.fillRect(0, 0, width, height);
    ctx.restore();

    // 绘制所有子节点
    nodes.forEach((node) => node.draw(ctx));
  }
  /**
   * Methods
   */
  /**
   * 设置背景纯色填充颜色
   * @param {string} color
   */
  setBgFillColor(color) {
    this.bgFillColor = color;
    this.stage?.draw();
  }
}

// 创建马赛克块图案
const blockSize = 20; // 马赛克块的尺寸
const patternCanvas = new Canvas({ width: blockSize, height: blockSize, pixelRatio: 1 });
const patternCtx = patternCanvas.getContext();
patternCtx.fillStyle = '#fff';
patternCtx.fillRect(0, 0, blockSize, blockSize);
patternCtx.fillStyle = '#eee';
patternCtx.fillRect(0, 0, blockSize / 2, blockSize / 2);
patternCtx.fillRect(blockSize / 2, blockSize / 2, blockSize / 2, blockSize / 2);
Board.mosaicPattern = patternCanvas.el;
